package filehanlderimpl;

import filehandler.FileHandler;

import java.io.UnsupportedEncodingException;
import java.util.Scanner;

/**
 * 控制台格式输入
 * Created by weijianyu on 2017/1/16.
 */
public class StdInHandler implements FileHandler {
    private String buffer = "";
    private int curPos = 0;

    public void open() {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            String line = scanner.nextLine();
            if ("end".equals(line)) {
                break;
            }
            buffer += line;
        }
        scanner.close();
    }

    public int close() {
        return 0;
    }

    public int read(byte[] buf, int begin, int len) {

        if (curPos >= buffer.length()) {
            return 0;
        }

        int readCnt = 0;
        try {
            byte[] inputBuf = buffer.getBytes("UTF8");
            while (curPos + readCnt < buffer.length() && readCnt < len) {
                buf[begin + readCnt] = inputBuf[curPos + readCnt];
                readCnt++;
            }
        } catch (UnsupportedEncodingException e) {
            // TODO: 2017/1/17  Auto-generated catch block
            e.printStackTrace();
        }

        return readCnt;
    }
}
